/* Copyright © 2010 LPRM
Universidade Federal do Espírito Santo - RNP-GT CWTools

This file is part of GW-Android.

GW-Android is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

GW-Android is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with GW-Android. If not, see <http://www.gnu.org/licenses/>. */
package br.ufes.cwtools.android.components;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.Calendar;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.cookie.Cookie;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.InputStreamBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;

import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import br.ufes.cwtools.android.Component;
import br.ufes.cwtools.android.R;

public class ImageUploader extends Component {
	private static final String TAG = "ImageUploader";

	private static final String EXTRA_IMAGE_URI = "image_uri";
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.component_image_uploader);
		
		String sUri = this.getIntent().getStringExtra(EXTRA_IMAGE_URI);
		if (sUri == null) {
			Log.w(TAG, "Missing required extra: image URI.");
//			this.finish();
			return;
		} else {
			Log.d(TAG, EXTRA_IMAGE_URI + ": " + sUri);
			// FIXME A imagem geralmente é muito grande e esgota a memória do aparelho;
			// é necessário carregar o thumbnail (ou gerar um, se não houver).
			// Coloca um thumbnail da imagem selecionada na tela.
//			Uri uri = Uri.parse(sUri);
//			ImageView v = (ImageView) this.findViewById(R.id.image_preview);
//			v.setImageURI(uri);
//			v.setVisibility(View.VISIBLE);
		}
	}
	
	public void confirmOnClick(View view) {
		//TODO Validação dos campos
//		this.login();
		this.postData();
		
		Log.d(TAG, "Confirmado; finalizando componente.");
		this.finish();
	}
	
//	private static final String ECHO_URI = "http://joinus.inf.ufes.br:8080/JoinUs-ApplicationServer/GetPost?teste=saida";
//	private static final String FORM_ACTION_PHOTO = "http://10.50.9.31:8080/GW-Application-Arquigrafia/groupware-workbench/6/photo/registra";
	private static final String FORM_ACTION_PHOTO = "http://192.168.1.3:8080/GW-Application-Arquigrafia/groupware-workbench/6/photo/registra";
	private static final String INPUT_NAME_ID = "photoRegister.id";
	private static final String INPUT_NAME_NAME = "photoRegister.nome";
	private static final String INPUT_NAME_DESCRIPTION = "photoRegister.descricao";
	private static final String INPUT_NAME_LOCATION = "photoRegister.lugar";
	private static final String INPUT_NAME_TAGS = "tagMgr.tags";
	private static final String INPUT_NAME_DATE = "photoRegister.data";
	private static final String INPUT_NAME_PHOTO = "foto";

//	<form name="photoRegisterForm" method="post" enctype="multipart/form-data"
//    action="/GW-Application-Arquigrafia/groupware-workbench/6/photo/registra">
//	<input type="hidden" name="photoRegister.id" value="" />
//	<input type="text" name="photoRegister.nome">
//	<textarea name="photoRegister.descricao"></textarea>
//	<input type="text" name="photoRegister.lugar">
//	<textarea name="tagMgr.tags"></textarea>
//	<input type="text" name="photoRegister.data" />
//	<input type="file" name="foto" />
//	</form>
	
	private void postData() {
		String id = "";  // Intencionalmente vazio.
		String name = ((EditText) this.findViewById(R.id.image_name)).getText().toString().trim();
		String description = ((EditText) this.findViewById(R.id.image_description)).getText().toString().trim();
		String location = "#GPS_DATA";  // TODO
		String tags = "origem:android";  // TODO Podemos especificar alguma tag aqui.
		Calendar calendar = Calendar.getInstance();
		String date = String.format("%02d/%02d/%04d", calendar.get(Calendar.DAY_OF_MONTH), calendar.get(Calendar.MONTH), calendar.get(Calendar.YEAR));
		// FIXME Verificar o formato da data, está aparecendo errado no site.
		
		String uri = this.getIntent().getStringExtra(EXTRA_IMAGE_URI);
		InputStream is = null;
		if (uri != null) {  // TODO Usar apenas a verificação no onCreate() quando os testes terminarem.
			try {
				is = this.getContentResolver().openInputStream(Uri.parse(uri));
			} catch (FileNotFoundException e) {
				Log.w(TAG, "File not found.");
//				this.finish();
				return;
			}
		}
		
		DefaultHttpClient httpClient = this.app.getHttpClient();
		HttpPost httpPost = new HttpPost(FORM_ACTION_PHOTO);
		try {
			MultipartEntity entity = new MultipartEntity();
			entity.addPart(INPUT_NAME_ID, new StringBody(id));
			entity.addPart(INPUT_NAME_NAME, new StringBody(name));
			entity.addPart(INPUT_NAME_DESCRIPTION, new StringBody(description));
			entity.addPart(INPUT_NAME_LOCATION, new StringBody(location));
			entity.addPart(INPUT_NAME_TAGS, new StringBody(tags));
			entity.addPart(INPUT_NAME_DATE, new StringBody(date));
			entity.addPart(INPUT_NAME_PHOTO, new InputStreamBody(is, "teste.jpg"));
			httpPost.setEntity(entity);
			
			HttpResponse response = httpClient.execute(httpPost);
			// TODO Verificar se o envio foi bem sucedido.
			// TODO Pegar o ID da foto no site e passar ao componente Binomios.
			is.close();  // TODO Verificar necessidade.
			
			// Imprime os cookies no log.
			List<Cookie> biscoitos = httpClient.getCookieStore().getCookies();
			for (Cookie passatempo : biscoitos) {
				Log.d(TAG + "#COOKIE", passatempo.toString());
			}
			
			// Imprime a resposta no log.
			BufferedReader bf = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
			String line;
			int limit = 10;
			while (limit-- > 0 && (line = bf.readLine()) != null) Log.d(TAG + "#RESPONSE", line);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
